package com.gdth.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONObject;

import com.gdth.utils.DownloadUtil;
import com.gdth.bank.BankApplication;
import com.gdth.bank.utils.LogUtils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class AppUpdate {
	private String TAG = "AppUtil";
	
	private static AppUpdate instance;
	
	private Context mContext;
	
	public static AppUpdate getInstance(Context mContext){
		if (instance == null){
			instance = new AppUpdate(mContext);
		}
		
		return instance;
	}
	
	public AppUpdate(Context mContext){
		this.mContext = mContext;
	}
    
    private int newVerCode;
    private String newVerName;
    
    public void updateApp(){
    	boolean isTrue = getServerCode(null);
    	if (isTrue) {  
            if (newVerCode > BankApplication.versionCode) {  
                doNewVersionUpdate(); // 更新新版本  
            } else {  
                notNewVersionShow(); // 提示当前为最新版本  
            }  
        }
    }
    
    /**
     * 获取最新的版本号
     * @param [{\"appname\":\"清远地税局\",\"apkname\":\"dishui.apk\",\"verName\":1.0.1,\"verCode\":2}]
     * @return
     */
    private boolean getServerCode(String verjson) {  
        try {  
            JSONArray array = new JSONArray(verjson);  
            if (array.length() > 0) {  
                JSONObject obj = array.getJSONObject(0);  
                try {  
                    newVerCode = Integer.parseInt(obj.getString("verCode"));  
                    newVerName = obj.getString("verName");  
                } catch (Exception e) {  
                    newVerCode = -1;  
                    newVerName = "";  
                    return false;  
                }  
            }  
        } catch (Exception e) {  
        	LogUtils.e(TAG, e.getMessage());  
            return false;  
        }  
        return true;  
    }
    
    private void notNewVersionShow() {  
        StringBuffer sb = new StringBuffer();  
        sb.append("当前版本:");  
        sb.append(BankApplication.versionName);  
        sb.append(" Code:");  
        sb.append(BankApplication.versionCode);  
        sb.append(",/n已是最新版,无需更新!");  
        Dialog dialog = new AlertDialog.Builder(mContext).setTitle("软件更新")  
            .setMessage(sb.toString())// 设置内容  
            .setPositiveButton("确定",// 设置确定按钮  
                new DialogInterface.OnClickListener() {  
                    @Override  
                    public void onClick(DialogInterface dialog, int which) {  
//                        finish();  
                    }  
                }).create();// 创建  

        dialog.show();  
    }  
    
    private ProgressDialog pBar;
    
    private void doNewVersionUpdate() {  
        StringBuffer sb = new StringBuffer();  
        sb.append("当前版本:");  
        sb.append(BankApplication.versionName);  
        sb.append(" Code:");  
        sb.append(BankApplication.versionCode);  
        sb.append(", 发现新版本:");  
        sb.append(newVerName);  
        sb.append(" Code:");  
        sb.append(newVerCode);  
        sb.append(", 是否更新?");  
        Dialog dialog = new AlertDialog.Builder(mContext)  
                .setTitle("软件更新")  
                .setMessage(sb.toString())  
                // 设置内容  
                .setPositiveButton("更新",// 设置确定按钮  
                        new DialogInterface.OnClickListener() {  
                            @Override  
                            public void onClick(DialogInterface dialog,  
                                    int which) {  
                                pBar = new ProgressDialog(mContext);  
                                pBar.setTitle("正在下载");  
                                pBar.setMessage("请稍候...");  
                                pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);  
                                downFile(null);  
                            }  
                        })  
                .setNegativeButton("暂不更新",  
                        new DialogInterface.OnClickListener() {  
                            public void onClick(DialogInterface dialog,  
                                    int whichButton) {  
                                // 点击"取消"按钮之后退出程序  
//                                finish();  
                            }  
                        }).create();// 创建  
        // 显示对话框  
        dialog.show();  
    }
    
    private void downFile(final String url) {  
        pBar.show();  
        new Thread() {  
            public void run() {   
                try {   
                    InputStream is = DownloadUtil.downloanFile(url);  
                    FileOutputStream fileOutputStream = null;  
                    if (is != null) {  
                        File file = new File("");  
                        fileOutputStream = new FileOutputStream(file);  
                        byte[] buf = new byte[1024];  
                        int ch = -1;    
                        while ((ch = is.read(buf)) != -1) {  
                            fileOutputStream.write(buf, 0, ch);
                        }  
                    }  
                    fileOutputStream.flush();  
                    if (fileOutputStream != null) {  
                        fileOutputStream.close();  
                    }  
                    
                    Message mMessage = new Message();
                    mMessage.what = 1;
                    appUpdateHandler.handleMessage(mMessage); 
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                
            	update();
            }  
        }.start();  
    }
    
    /**
     * 通知更新
     */
    private Handler appUpdateHandler = new Handler(new Handler.Callback() {
		
		@Override
		public boolean handleMessage(Message arg0) {
			// TODO Auto-generated method stub
			if (arg0.what == 1){
				pBar.cancel();  
                update();  
			}
			return false;
		}
	});
    
    /**
     * 安装更新的Apk
     */
    private void update() {  
    	Intent intent = new Intent(Intent.ACTION_VIEW);  
        
    	intent.setDataAndType(Uri.fromFile(new File("")), "application/vnd.android.package-archive");  
        
        mContext.startActivity(intent);  
    }
}
